<template>
  <div class="content">

    <!--搜索-->
    <div ref="searchDiv">
      <a-form
          ref="defSearch"
          :model="defSearch.param"
          :rules="defSearch.rules"
          :labelCol="defSearch.labelCol"
          class="search_form shadow3">

        <!--搜索条件-->
        <div class="fx_row fx_wrap fx_start" style="width: calc(100%)">
          <a-form-item label="职位名称" name="name" style="width: 220px">
            <a-input allow-clear v-model:value="defSearch.param.name" placeholder="请输入职位名称"></a-input>
          </a-form-item>
          <a-form-item label="职位编码" name="code" style="width: 220px">
            <a-input allow-clear v-model:value="defSearch.param.code" placeholder="请输入职位编码"></a-input>
          </a-form-item>

          <a-form-item label="职位状态" name="status" style="width: 220px">
            <a-select v-model:value="defSearch.param.status" placeholder="请选择" :allowClear="true">
              <a-select-option v-for="(item,index) in option.status" :value=item.value>
                {{
                  item.label
                }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </div>
        <!--按钮-->
        <a-form-item class="search_button_2">
          <a-button type="primary" @click.stop="search" class="font12">
            <template #icon>
              <SearchOutlined/>
            </template>
            查询
          </a-button>
          <a-button style="margin-left: 10px" @click.stop="()=>{ resetForm('defSearch'); }" class="font12">
            <template #icon>
              <UndoOutlined/>
            </template>
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </div>

    <!--表格选项-->
    <div class="table_tools">
      <a-button class="font11" type="primary" size="small" ghost @click.stop="openAdd(null)">
        <template #icon>
          <plus-outlined/>
        </template>
        新建
      </a-button>
      <!--      <a-divider type="vertical"/>-->
      <!--      <a-button class="font11" type="primary" size="small" ghost>删除</a-button>-->

      <div style="flex: 1 1 0"></div>

      <a-tooltip placement="top">
        <template #title>
          <span>批量删除</span>
        </template>
        <delete-outlined :style="{fontSize: '16px'}" @click.stop="delAPIBatch"/>
      </a-tooltip>

      <a-divider type="vertical"/>

      <a-tooltip placement="top">
        <template #title>
          <span>表格大小</span>
        </template>
        <a-dropdown :trigger="['click']">
          <setting-outlined :style="{fontSize: '16px'}"/>
          <template #overlay>
            <a-menu v-model:selectedKeys="defTable.size" @click="(item)=>{defTable.size=item.key+''}">
              <a-menu-item v-for="(item,index) in option.tableSize" :key="item.value">
                <div style="padding: 0 5px">
                  {{ item.label }}
                </div>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>

      </a-tooltip>

      <!--      <a-divider type="vertical"/>-->

      <!--      <a-tooltip placement="top">-->
      <!--        <template #title>-->
      <!--          <span>全屏</span>-->
      <!--        </template>-->
      <!--        <fullscreen-outlined :style="{fontSize: '16px'}"/>-->
      <!--      </a-tooltip>-->
      <!--          <a style="margin-left: 10px">-->
      <!--            <file.ts-add-outlined style="color: #1890FF;font-size: 10px;"/>-->
      <!--            新增</a>-->
      <!--          <a style="margin-left: 10px">-->
      <!--            <edit-outlined style="color: #1890FF;font-size: 10px;"/>-->
      <!--            编辑</a>-->
      <!--          <a style="margin-left: 10px;padding:2px;">-->
      <!--            <delete-outlined style="color: #1890FF;font-size: 10px;"/>-->
      <!--            删除</a>-->
    </div>

    <!--表格-->
    <div ref="tableDiv" :style="{background:'#FFFFFF',minHeight:option.tableMinHeight}">
      <a-table
          sticky
          ref="defTable"
          rowKey="id"
          :pagination="false"
          :size="defTable.size"
          :columns="defTable.column"
          :expandRowByClick="true"
          :data-source="defTable.data"
          :rowSelection="defTable.rowSelection()"
          @resizeColumn="(w, col) => {col.width = w;}">

        <!--表格内容-->
        <template #bodyCell="{ text, record, index, column  }">

          <template v-if="column.dataIndex === 'name'">
            <a-tag>
              {{ text }}
            </a-tag>
          </template>

          <template v-if="column.dataIndex === 'code'">
            <a-tag color="blue">
              {{ text }}
            </a-tag>
          </template>

          <template v-if="column.dataIndex === 'status'">
            <a-tag v-if="text==0" color="green" class="round">启用</a-tag>
            <a-tag v-if="text==1" color="orange" class="round">停用</a-tag>
          </template>


          <!--操作-->
          <template v-if="column.dataIndex === 'action'">

            <!--编辑-->
            <a @click.stop="openEdit(record)" class="table_action_a">编辑</a>

            <!--删除-->
            <a-divider type="vertical"/>
            <a-popconfirm placement="bottomRight" ok-text="确定" cancel-text="取消"
                          @click.stop @confirm="deleteAPI(record)">
              <template #title>
                <p>是否执行删除操作?</p>
              </template>
              <a class="table_action_a">删除</a>
            </a-popconfirm>

          </template>

        </template>

      </a-table>
    </div>

    <!--分页-->
    <Pagination class="table_page"
                :current="defPage.current"
                :total="defPage.total"
                :page-size="defPage.size"
                @change="defPage.change"/>

    <!--新增Dialog-->
    <a-modal
        title="新增职位"
        style="min-width: 800px"
        :maskClosable="false"
        :destroyOnClose="true"
        v-model:visible="option.openAdd">

      <!--新增表单-->
      <a-form
          ref="defForm"
          label-align="right"
          :model="defForm.data"
          :rules="defForm.rules"


          class="go_shadow go_radius">

        <a-form-item label="职位名称" name="name">
          <a-input v-model:value="defForm.data.name" placeholder="请输入职位名称" :allowClear="true"/>
        </a-form-item>

        <a-form-item label="职位编码" name="code">
          <a-input v-model:value="defForm.data.code" placeholder="请输入职位编码" :allowClear="true"/>
        </a-form-item>

        <a-form-item label="职位状态" name="status">
          <a-radio-group v-model:value="defForm.data.status">
            <a-radio value="0">启用</a-radio>
            <a-radio value="1">停用</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="排序" name="sort">
          <a-input-number v-model:value="defForm.data.sort" :min="1" :max="99999"/>
        </a-form-item>

        <a-form-item label="描述信息" name="desc">
          <a-textarea show-count :maxlength="200" v-model:value="defForm.data.desc" placeholder="请输入描述信息" :rows="3"/>
        </a-form-item>

      </a-form>

      <!--底部按钮-->
      <template #footer>
        <a-button @click.stop="()=>{option.openAdd = false}">取消</a-button>
        <!--        <a-button @click.stop="()=>{resetForm('defForm')}">重置</a-button>-->
        <a-button type="primary" @click.stop="addPost">保存</a-button>
      </template>

    </a-modal>

    <!--编辑Dialog-->
    <a-modal
        title="编辑职位"
        style="min-width: 800px"
        :maskClosable="false"
        :destroyOnClose="true"
        v-model:visible="option.openEdit">

      <!--新增表单-->
      <a-form
          ref="defForm"
          label-align="right"
          :model="defForm.data"
          :rules="defForm.rules"


          class="go_shadow go_radius">

        <a-form-item label="职位名称" name="name">
          <a-input v-model:value="defForm.data.name" placeholder="请输入职位名称" :allowClear="true"/>
        </a-form-item>

        <a-form-item label="职位编码" name="code">
          <a-input v-model:value="defForm.data.code" placeholder="请输入职位编码" :allowClear="true"/>
        </a-form-item>

        <a-form-item label="职位状态" name="status">
          <a-radio-group v-model:value="defForm.data.status">
            <a-radio value="0">启用</a-radio>
            <a-radio value="1">停用</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="排序" name="sort">
          <a-input-number v-model:value="defForm.data.sort" :min="1" :max="99999"/>
        </a-form-item>

        <a-form-item label="描述信息" name="desc">
          <a-textarea show-count :maxlength="200" v-model:value="defForm.data.desc" placeholder="请输入描述信息" :rows="3"/>
        </a-form-item>

      </a-form>

      <!--底部按钮-->
      <template #footer>
        <a-button @click.stop="()=>{option.openEdit = false}">取消</a-button>
        <!--        <a-button @click.stop="()=>{resetForm('defForm')}">重置</a-button>-->
        <a-button type="primary" @click.stop="editPost">保存</a-button>
      </template>

    </a-modal>

  </div>
</template>

<script lang="ts">
import {DeleteOutlined, PlusOutlined, SearchOutlined, UndoOutlined} from "@ant-design/icons-vue";
import {requiredBlur, requiredChange} from "@/common/util/validate";
import {useUserStore} from "@/common/store/modules/user";
import {ModalKit} from "@/common/util/ModalKit";
import {useLayoutStore} from "@/common/store/modules/layout";
import Pagination from "@/common/component/Pagination.vue";
import {copyObj} from "@/common/util/kit";
import {parseTree} from "@/common/util/tree";

export default {
  components: {Pagination, DeleteOutlined, SearchOutlined, UndoOutlined, PlusOutlined},
  mounted() {
    this.queryPage()
    //全局监听-刷新当前页面
    this.$event.$on('refresh', (data) => {
      if (this.$route.path == data['path']) {
        this.resetForm('defSearch');
        this.queryPage()
      }
    })
    //更新表格大小
    this.$nextTick(() => {
      this.calcDefaultTableHeight()
    })
    //监控窗口大小变更
    window.onresize = () => {
      this.calcDefaultTableHeight()
    }
  },
  data() {
    return {
      //store
      userStore: useUserStore(),
      //选项
      option: {
        openAdd: false,
        openEdit: false,
        openInfo: false,
        tableMinHeight: '100%',
        tableSize: [
          {label: '大号', value: 'default'},
          {label: '中号', value: 'middle'},
          {label: '小号', value: 'small'},
        ],
        status: [
          {label: '已启用', value: '0'},
          {label: '已停用', value: '1'},
        ],
      },

      //搜索表单（默认）
      defSearch: {
        param: {
          module_name: undefined,
          api_name: undefined,
          path: undefined,
          use_state: undefined,
        },
        rules: {},
        labelCol: {style: {width: '60px'}},
      },

      //表单（默认）
      defForm: {
        //实际表单数据
        data: {},
        initData: {
          name: undefined,
          status: '0',
          code: undefined,
          sort: '100',
        },
        rules: {
          name: [requiredBlur],
          status: [requiredBlur],
          code: [requiredBlur],
          sort: [requiredBlur],
        },

      },

      //表单（菜单功能）
      funForm: {
        //实际表单数据
        data: {
          sort: 1,
          menuName: undefined,
          name: undefined,
          apis: [],
        },
        rules: {
          name: [requiredBlur],
          sort: [requiredBlur],
          apis: [requiredChange],
        },
      },

      //表格数据（默认）
      defTable: {
        size: 'middle',
        data: [],
        column: [
          {title: 'ID', dataIndex: 'id', ellipsis: true, width: 100, align: 'center', resizable: true},
          {title: '职位名称', dataIndex: 'name', resizable: true,},
          {title: '职位编码', dataIndex: 'code', resizable: true},
          {title: '状态', dataIndex: 'status', resizable: true, align: 'center'},
          {title: '排序', dataIndex: 'sort', resizable: true, align: 'center', width: 80},
          {title: '描述信息', dataIndex: 'desc', resizable: true, ellipsis: true},
          {title: '操作', dataIndex: 'action', align: 'center', width: 180},
        ],
        selectKey: [],
        selectRow: [],
        rowSelection: () => {
          return {
            type: "checkbox",
            checkStrictly: false,
            preserveSelectedRowKeys: false,//翻页后保留选中状态
            selectedRowKeys: this.defTable.selectKey,
            onChange: (selectedRowKeys, selectedRows) => {
              this.defTable.selectKey = selectedRowKeys
              this.defTable.selectRow = selectedRows
            },
            onSelect: (record, selected, selectedRows) => {
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
            },
          }
        },
      },

      //分页（默认）
      defPage: {
        current: 1,
        size: 10,
        total: 0,
        type: 'small',
        change: (current, pageSize) => {
          this.defPage.current = current;
          this.defPage.size = pageSize;
          this.queryPage()
        }
      },
    }
  },
  methods: {
    //查询分页
    async queryPage() {
      //加载中
      useLayoutStore().pageLoading = true;
      //参数
      let param = copyObj(this.defSearch.param)
      //分页
      param.size = this.defPage.size
      param.current = this.defPage.current

      this.$http.post('/system/post/list', param).then((res) => {
        //分页
        this.defPage.total = res.total * 1
        //数据
        this.defTable.data = parseTree(res.data)
        useLayoutStore().pageLoading = false;
      })
    },
    //搜索
    search() {
      this.$refs.defSearch.validate().then(() => {
        this.queryPage()
      }).catch(error => {
        this.$message.warning("存在错误，请检查表单填写情况。", 2)
      });

    },
    //重置表单（还原）
    resetForm(formName) {
      let form = this.$refs[formName]
      if (form) {
        form.resetFields()
      }
    },
    //打开新增Dialog
    async openAdd(record) {
      this.defForm.data = copyObj(this.defForm.initData)
      this.option.openAdd = true;
    },
    //打开编辑菜单Dialog
    async openEdit(record) {
      await this.queryPage();

      this.defForm.data = copyObj(record);
      this.option.openEdit = true;
    },
    //添加
    addPost(record) {
      this.$refs.defForm.validate()
          .then(() => {
            let submitForm = copyObj(this.defForm.data)
            //console.log("【addApi-submitForm】", JSON.stringify(submitForm))

            this.$http.post("/system/post/add", submitForm).then((res) => {
              this.$message.success(res.message,1)
              this.queryPage()
              this.option.openAdd = false
            })

          })
          .catch(error => {
            this.$message.warning("存在错误，请检查表单填写情况。", 2)
          });
    },
    //编辑
    editPost(record) {
      this.$refs.defForm.validate()
          .then(() => {
            let submitForm = copyObj(this.defForm.data)
            //console.log("【edit-submitForm】", JSON.stringify(submitForm))

            this.$http.post("/system/post/edit", submitForm).then((res) => {
              this.$message.success(res.message,1)
              this.queryPage()
              this.option.openEdit = false
            })

          })
          .catch(error => {
            this.$message.warning("存在错误，请检查表单填写情况。", 2)
          });
    },
    //删除
    deleteAPI(record) {
      this.$http.post("/system/post/del", {ids: [record.id]}).then((res) => {
        this.$message.success(res.message,1)
        this.queryPage()
      })
    },
    //批量删除
    delAPIBatch() {
      let keys = this.defTable.selectKey;
      if (keys.length === 0) {
        this.$message.warn("请至少勾选一项", 1)
        return
      }
      ModalKit.confirm(
          `已勾选${keys.length}条数据，是否执行批量删除？`,
          () => {
            this.$http.post("/system/post/del", {ids: keys}).then((res) => {
              this.$message.success(res.message,1)
              this.queryPage()
            })
          },
          () => {
            this.$message.warning("操作已取消", 1)
          })

    },
    //计算表格高度，最小要求铺满窗口
    calcDefaultTableHeight() {
      //减去 （搜索表单、表格工具栏、外边距、分页(60px)）
      let searchDiv = this.$refs.searchDiv.offsetHeight
      let tableToolDiv = 50
      let margin = 32;
      let page = 60

      this.option.tableMinHeight = `calc(100% - ${searchDiv}px - ${tableToolDiv}px - ${margin}px - ${page}px)`;
      //console.log(" searchDiv ", searchDiv)
      //console.log(" tableToolDiv ", tableToolDiv)
      //console.log(" this.defTable.minHeight", this.defTable.minHeight)
    },
  }
}


</script>

<style lang="less">

</style>

<style scoped lang="less">

</style>